#ifndef LIVETRACKAUTOSAVER_H
#define LIVETRACKAUTOSAVER_H

#include <QtCore>

#include "gps_track.h"

#define AS_TITLE "T"
#define AS_DESC "D"
#define AS_POINT "P"
#define AS_WAYPOINT "W"
#define AS_BACK "B"
#define AS_LEG "L"
#define AS_ACTIVE_LEG "A"
#define AS_FILENAME "F"
#define AS_DELETE_LEG "X"
#define AS_DELETE_WAYPOINT "Y"

#define AS_TITLE_SEP AS_TITLE" "
#define AS_DESC_SEP AS_DESC" "
#define AS_POINT_SEP AS_POINT" "
#define AS_WAYPOINT_SEP AS_WAYPOINT" "
#define AS_BACK_SEP AS_BACK" "
#define AS_LEG_SEP AS_LEG" "
#define AS_ACTIVE_LEG_SEP AS_ACTIVE_LEG" "
#define AS_FILENAME_SEP AS_FILENAME" "
#define AS_DELETE_LEG_SEP AS_DELETE_LEG" "
#define AS_DELETE_WAYPOINT_SEP AS_DELETE_WAYPOINT" "

class WorkerAutoSave;
class WorkerAutoLoad;
class LiveTrack;

class LiveTrackAutosaver: public QObject
{
    Q_OBJECT
public:
    friend class WorkerAutoSave;
    friend class WorkerAutoLoad;

    explicit LiveTrackAutosaver();
    ~LiveTrackAutosaver();

    bool initialize(LiveTrack*);

    bool AutosaveEnabled() const;

    void AutosavePrecache();
    bool AutosaveStart();
    void AutosaveStop();
    void AutosaveBacktrack(int);
    void AutosavePoint( int, const GPS_point* );
    void AutosaveWaypoint( const GPS_waypoint* );
    void AutosaveLeg(const GPS_leg*);
    void AutosaveTitle(const QString&);
    void AutosaveDescription(const QString&);
    void AutosaveActiveLeg(int);
    void AutosaveDeleteLeg(int);
    void AutosaveDeleteWaypoint(int);
    void AutosaveFilename(const QString&);

private slots:
    // activate/deactivate autosave feature
    void updateAutosave(bool);

private:
    // STATIC section. This is used both by this class and WorkerAutosave.
    static QString formatBacktrack(int);
    static QString formatPoint(int, const GPS_point*);
    static QString formatWaypoint(const GPS_waypoint*);
    static QString formatLeg(const GPS_leg* );
    static QString formatTitle(const QString&);
    static QString formatDescription(const QString&);
    static QString formatActiveLeg(int);
    static QString formatDeleteLeg(int);
    static QString formatDeleteWaypoint(int);
    static QString formatFilename(const QString&);

    static GPS_point* readPoint(QTextStream&, int&);
    static GPS_leg* readLeg(QTextStream&, GPS_leg* leg = NULL);
    static GPS_waypoint* readWaypoint(QTextStream&, GPS_waypoint* wp = NULL);
    static int readId(QTextStream&);
    static QString readString(QTextStream&);

private:
    bool autosave;
    QFile autosave_file;
    LiveTrack* livetrack;

    bool keepAutosave;

};

#endif // LIVETRACKAUTOSAVER_H
